<?php defined('SYSPATH') or die('No direct script access.');

class Model_Shop extends ORM
{  
    protected $_reload_on_wakeup = false;
    protected static $_current = null;             // current
    
    public function add_shop($url)
    {
        /*if (!Valid::url($url)) {
            throw new Model_Exception('Некорректный адрес магазина');
        } */
        
        $this->url  = $url;
        $this->save();
        
        return $this;  
    }
    
    public function edit_shop($name, $url, $parse_url = null)
    {       
        /*if (!Valid::url($url)) {
            throw new Model_Exception('Некорректный адрес магазина');
        }*/
        
        if (!trim($parse_url)) {
            $parse_url = null;   
        }
        
        if ($parse_url && !Valid::url($parse_url)) {
            throw new Model_Exception('Некорректная ссылка на YML-файл');  
        }
        
        $this->name = $name;
        $this->url  = $url;
        $this->parse_url = $parse_url;
        $this->save();
    }
    
    public function is_parse_local()
    {   
        return true;
        
        // TODO    
        if ($this->parse_url) {
            return false;
        }
        return true;
    }
    
    public function get_parse_local_path()
    {       
        return APPPATH . '../data/feeds/' . $this->id . '.xml';
    }
    
    public function set_as_current()
    {
        self::$_current = $this; 
    } 
    
    public function get_current()
    {
        return self::$_current;
    }
    
    public function get_widget_layout()
    {
        if ($this->is_custom_design()) {
            return 'widget/_custom/' . $this->get_current()->id . '/layout_tpl';
        } 
        return 'widget/layout_tpl';   
    }
    
    public function get_widget_view($path)
    {
        if ($this->is_custom_design()) {
            return new View('widget/_custom/' . $this->get_current()->id . '/' . $path);    
        }
        return new View('widget/' . $path);
    }
    
    public function is_custom_design()
    {
        if (is_dir(APPPATH . 'views/widget/_custom/' . $this->get_current()->id . '/')) {
            return true;
        }
        return false;
    }
}